package com.example.myblogserver.service.impl;

import com.example.myblogserver.common.utils.RedisUtil;
import com.example.myblogserver.dto.CommentDTO;
import com.example.myblogserver.model.Comments;
import com.example.myblogserver.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.myblogserver.mapper.CommentsMapper;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private RedisUtil RedisUtil;

    @Override
    public void addComment(CommentDTO commentDTO) {
        // 验证码校验
        if (!commentDTO.getCode().equals(RedisUtil.getCode("email:code:" +commentDTO.getAuthorEmail()))) {
            throw new RuntimeException("验证码错误");
        }

        // 将 CommentDTO 转换为 Comments 实体
        //如果内容太长，才现在长度
        if (commentDTO.getContentHtml().length() > 300) {
            commentDTO.setContentHtml(commentDTO.getContentHtml().substring(0, 300));
        }
        //防止评论有跨站脚本
        commentDTO.setContentHtml(commentDTO.getContentHtml().replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
        if (commentDTO.getAuthorName().length() > 50) {
            commentDTO.setAuthorName(commentDTO.getAuthorName().substring(0, 50));
        }
        //用户名防止跨站脚本
        commentDTO.setAuthorName(commentDTO.getAuthorName().replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
        Comments commentEntity = new Comments();
        BeanUtils.copyProperties(commentDTO , commentEntity);

        // 插入数据库
        commentsMapper.insert(commentEntity);
    }

    @Override
    public List<Comments> getCommentsByArticleId(Long articleId) {
        return commentsMapper.getCommentsByArticleId(articleId);
    }

}
